import {Component, EventEmitter, Input, OnChanges, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {UserInfoModel} from '../../../../models/user-info.model';
import {ApiUrl} from '../../../../config/api-url';
import {BaseService} from '../../../../shared/service/base.service';
import {QuillModule} from 'ngx-quill';

@Component({
  selector: 'app-notice-edit',
  templateUrl: './notice-edit.component.html',
  styleUrls: ['./notice-edit.component.less']
})
export class NoticeEditComponent implements OnInit, OnChanges {

  // 模态框表单
  formModel: FormGroup;
  // 加载动画
  isOkLoading: boolean;
  @Input()
  isVisible = false;
  // 两种情况：1、这是单纯的添加，所以是null。2、修改操作，外面传了一个对象
  @Input()
  notice;
  @Output()
  emitVisible: EventEmitter<any> = new EventEmitter();
  userInfo: UserInfoModel = new UserInfoModel();
  // 编辑内容
  context: any;
  quill: QuillModule;


  constructor(private fb: FormBuilder,
              public baseService: BaseService
  ) {
    this.buildForm();
  }

  ngOnInit(): void {
  }

  ngOnChanges() {
    if (this.notice == null) {
      return;
    }
    // 初始化修改
    this.formModel = this.fb.group({
      id: this.notice.id,
      title: this.notice.title,
      agencyId: this.notice.agencyId,
      typeId: this.notice.typeId,
      content: this.notice.content,
      status: this.notice.status
    });
  }

  // 初始化表单数据
  buildForm() {
    // 初始化添加
    this.formModel = this.fb.group({
      id: [null, []],
      title: [null, [Validators.required]],
      agencyId: [0, []],
      typeId: ['1', []],
      content: [null, []],
      status: [1, []]
    });
  }

  // 确定编辑
  handleOk(): void {
    this.isOkLoading = true;
    for (const i in this.formModel.controls) {
      if (!this.formModel.controls[i].valid) {
        this.isOkLoading = false;
      }
      this.formModel.controls[i].markAsDirty();
      this.formModel.controls[i].updateValueAndValidity();
    }

    if (!this.isOkLoading) {
      return;
    }

    if (this.formModel.value.agencyId == 1) {
      this.formModel.value.agencyId = this.userInfo.agencyId;
    }

    console.log(this.context);
    this.commonHandle();
  }

  // 取消编辑
  handleCancel(): void {
    this.commonHandle();
  }

  // 公用，子传值给父
  commonHandle() {
    this.isOkLoading = false;
    this.isVisible = false;
    let body = {'isVisible': this.isVisible};
    this.emitVisible.emit(body);
  }


  editContent() {
    console.log(this.context);
  }

  // 选择框
  selectChange(value: number): void {
    this.formModel.controls['typeId'].setValue(value);
    console.log(this.formModel.value.typeId);
  }

  // 单选框
  radioChange(value: number): void {
    this.formModel.controls['status'].setValue(value);
  }
}
